package com.sikadwafastdaisfondturbo.pretloan.ui.credit.page

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.AmountAdapter
import com.sikadwafastdaisfondturbo.pretloan.adapter.CreditRepayLableAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageRepayBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.SikadwaNoticeDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.event.track.TrackEventManager
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaKefuConfigHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal
import androidx.core.net.toUri

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：待还款
 */
class RepayPage: ProFragment() {
    private var _binding: PageRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var mAmountAdapter: AmountAdapter? = null
    //还款明细
    private var mLableAdapter: CreditRepayLableAdapter? = null
    //是否展开
    private var isOpen = false

    //公告信息
    private var noticeDialog: SikadwaNoticeDialog? = null

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        _binding?.parentLayout?.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initRefreshView()
        initRvAmount()
        initRvRepayListView()
        showOpenOrCloseView()


        _binding?.imgLang?.visibility = View.GONE
        if (Configs.isTanzania()){
            _binding?.imgLang?.visibility = View.VISIBLE
        }
    }

    override fun initListener() {
        //切换语言
        _binding?.imgLang?.setOnClickListener {
            showSikadwaProLangDialog("CreditRepayment Page", onCheckSuccess = {

            })
        }
        _binding?.imgUser?.setOnClickListener {
            showPersonalDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_USER,"CreditRepayment Page")
        }
        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditRepayment Page")
        }
        //展开、收起
        _binding?.ivLable?.setOnClickListener {
            isOpen = !isOpen
            showOpenOrCloseView()
        }
        //还款
        _binding?.btnRepayment?.setOnClickListener {
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_CREDIT_REPAYMENT,"")
            showLoading()
            onPayAction()
        }
    }

    override fun initData() {
        showLoading()
        loadCreditRepayInfoAction()
        addEvent(EventType.PAGE.PAGE_CREDIT_REPAYMENT_START,"")
    }

    fun refreshAction(){
        loadCreditRepayInfoAction()
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)

            loadCreditRepayInfoAction()
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    private fun initRvAmount(){
        _binding?.rvAmount?.setHasFixedSize(true)
        _binding?.rvAmount?.isNestedScrollingEnabled = false
        _binding?.rvAmount?.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(14f)
        _binding?.rvAmount?.addItemDecoration(LinearDecoration(0,decoration,0,0))
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvAmount?.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(_binding?.rvAmount)
        mAmountAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter?.getItem(position)
        }
        _binding?.rvAmount?.adapter = mAmountAdapter
    }

    /**
     * 初始化列表
     */
    private fun initRvRepayListView() {
        _binding?.rvRepayInfo?.setHasFixedSize(true)
        _binding?.rvRepayInfo?.isNestedScrollingEnabled = false
        _binding?.rvRepayInfo?.isFocusableInTouchMode = false //不需要焦点
        _binding?.rvRepayInfo?.layoutManager = LinearLayoutManager(context)
//        val topDecoration = DensityUtils.dp2px(8f)
//        _binding?.rvRepayInfo?.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        mLableAdapter = CreditRepayLableAdapter(_binding?.rvRepayInfo)
        _binding?.rvRepayInfo?.adapter = mLableAdapter
        _binding?.rvRepayInfo?.itemAnimator = DefaultItemAnimator()
        mLableAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
        })
    }

    /**
     * 收起
     */
    private fun showOpenOrCloseView(){
        if (isOpen){//展开
            _binding?.rvRepayInfo?.visibility = View.VISIBLE
            _binding?.ivLable?.setImageResource(R.mipmap.img_credit_repay_up_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_OPEN,"")
        } else {
            _binding?.rvRepayInfo?.visibility = View.GONE
            _binding?.ivLable?.setImageResource(R.mipmap.img_credit_repay_down_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_CLOSE,"")
        }
    }

    /**
     * 设置还款信息
     */
    @SuppressLint("SetTextI18n")
    fun setRepaymentInfo(data: JSONObject) {
        val amountList = arrayListOf<String>()
        val amountString = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter?.data = amountList

        _binding?.textRepayAmount?.text = data.optString("repayAmount") + " " + data.optString("currency")
        _binding?.textRepayDate?.text = data.optString("repayDate")
        _binding?.textTotal?.text = data.optString("repayAmount")
        _binding?.textUnit?.text = data.optString("currency")

//        val jsArray = data.optJSONArray("repayList")
        val jsArray = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (jsArray != null) {
            for (i in 0..<jsArray.length()){
                dataList.add(jsArray.optJSONObject(i))
            }
        }
        mLableAdapter?.data = dataList

        //待还款显示公告信息
        showSikadwaNoticeDialog()
    }

    /**
     * 待还款 根据配置显示公告Dialog
     */
    private fun showSikadwaNoticeDialog(){
        // 在后台线程检查条件，避免主线程阻塞
        if (!shouldShowNoticeDialog()) {
            return
        }

        // 确保在主线程执行 UI 操作
        if (!isFragmentActive()) {
            return
        }

        createAndShowNoticeDialog()
    }

    /**
     * 创建并显示通知对话框
     */
    private fun createAndShowNoticeDialog() {
        if (!isFragmentActive()) {
            return
        }

        val noticeInfo = SikadwaKefuConfigHelper.takeSikadwaKefuNoticeInfo() ?: return

        // 更新显示次数
        SikadwaKefuConfigHelper.showNoticeNum = SikadwaKefuConfigHelper.showNoticeNum + 1

        noticeDialog = SikadwaNoticeDialog(requireContext(), "Repay Page",object : SikadwaNoticeDialog.IDialogCallback {
            override fun onClick(view: View?) {
                // 处理点击事件
            }
        })

        noticeDialog?.let { dialog ->
            // 最终检查后再显示
            if (isFragmentActive()) {
                dialog.show()
                dialog.setNoticeTitle(noticeInfo.optString("noticeTitle"))
                dialog.setNoticeMsg(noticeInfo.optString("noticeText"))
            }
        }
    }

    /**
     * 检查是否应该显示通知对话框
     */
    private fun shouldShowNoticeDialog(): Boolean {
        if (!SikadwaKefuConfigHelper.isSikadwaShowNotice()) {
            return false
        }

        val noticeInfo = SikadwaKefuConfigHelper.takeSikadwaKefuNoticeInfo() ?: return false
        val showNum = noticeInfo.optInt("num", 1)
        val num = SikadwaKefuConfigHelper.showNoticeNum

        if (num >= showNum) {
            return false
        }
        // 检查对话框是否已经在显示
        if (noticeDialog?.isShowing == true) {
            return false
        }
        return true
    }

    /**
     * 检查 Fragment 是否处于活跃状态
     */
    private fun isFragmentActive(): Boolean {
        return isAdded &&
                !isDetached &&
                activity != null &&
                !requireActivity().isFinishing &&
                !requireActivity().isDestroyed
    }

    /**
     * 跳转支付H5
     */
    private fun enterPayLink(payUrl: String){
        val uri = payUrl.toUri()
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * 获取还款信息
     */
    private fun loadCreditRepayInfoAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_INFO)
            put("oldFlag","YES")
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    //某些地区没有repayList，需要手动添加数据
                    if (!it.has("repayList") || it.optJSONArray("repayList") == null){
                        val unit = it.optString("currency")
                        val repayArray = JSONArray()
                        val amountItem = JSONObject()
                        amountItem.put("showName",getString(R.string.credit_repaylist_loan_amount))
                        amountItem.put("showDetail",it.optString("amount") + unit)
                        repayArray.put(amountItem)

                        val interestItem = JSONObject()
                        interestItem.put("showName",getString(R.string.credit_repaylist_interest))
                        interestItem.put("showDetail",it.optString("interest") + unit)
                        repayArray.put(interestItem)

                        val serviceFee = BigDecimal(it.optString("serviceFee")).stripTrailingZeros().toPlainString()
                        if (serviceFee.toDouble() > 0){
                            val serviceFeeItem = JSONObject()
                            serviceFeeItem.put("showName",getString(R.string.credit_repaylist_service_fee))
                            serviceFeeItem.put("showDetail",it.optString("serviceFee") + unit)
                            repayArray.put(serviceFeeItem)
                        }

                        val overdueDayItem = JSONObject()
                        overdueDayItem.put("showName",getString(R.string.credit_repaylist_overdue_days))
                        overdueDayItem.put("showDetail",String.format(getString(R.string.credit_repaylist_days),it.optString("overdueDay")))
                        repayArray.put(overdueDayItem)

                        val overduePenaltyItem = JSONObject()
                        overduePenaltyItem.put("showName",getString(R.string.credit_repaylist_overdue_penalty))
                        overduePenaltyItem.put("showDetail",it.optString("overdueAmount") + unit)
                        repayArray.put(overduePenaltyItem)
                        it.put("repayList",repayArray)
                    }
                    setRepaymentInfo(it)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 还款
     */
    private fun onPayAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_URL)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    var repayUrl = it.optString("repayUrl","")
                    if (repayUrl.isEmpty()){
                        repayUrl = it.optString("url")
                    }
                    enterPayLink(repayUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        //退出待还款页面立即上报所有埋点
        TrackEventManager.trackEventNow(EventType.PAGE.PAGE_CREDIT_REPAYMENT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        noticeDialog?.dismiss()
        noticeDialog = null
        _binding = null
    }
}